﻿using System;
using System.Collections.Generic;
using System.Text;
using RegionInterface;
using Common;
using UnityEngine;


public partial class AvatarModule : ModuleBase
{
    public AvatarHandle Owner;
    public List<AvatarHandle> ScenePlayers;
    public AvatarModule()
    {
        ScenePlayers = new List<AvatarHandle>();
        RegionStateManager.LoginStateChangeHandle += delegate(LoginState form, LoginState to)
        {
            if (to == LoginState.LogoutEnd)
            {
                DeletePlayer(ref Owner);
                for (int i = 0; i < ScenePlayers.Count; i++)
                {
                    AvatarHandle tmp = ScenePlayers[i];
                    DeletePlayer(ref tmp);
                }
                ScenePlayers.Clear();
            }
        };
        AppInterface.AvatarModule = this as IAvatarModule;
        AppInterface.NetworkModule.RegisterNetworkHandle(this as INetwork);
    }
    public AvatarHandle FindPlayer(int id)
    {
        for (int i = 0; i < ScenePlayers.Count; i++)
        {
            if (id == ScenePlayers[i].Id)
            {
                return ScenePlayers[i];
            }
        }
        return null;
    }
    private void DeletePlayer(ref AvatarHandle p)
    {
        OnIPlayerLogout(p as IAvatarHandle);
        GameObject.Destroy(p.Root);
        p = null;
    }
    public override void Update()
    {
        if (Owner != null) Owner.Update();
        foreach (AvatarHandle p in ScenePlayers)
        {
            p.Update();
        }
    }
    public override void FixedUpdate()
    {
        if (Owner != null) Owner.FixedUpdate();
        foreach (AvatarHandle p in ScenePlayers)
        {
            p.FixedUpdate();
        }
    }
}